import * as React from "react";
import { observer } from "mobx-react";
import { observable } from "mobx";
import {
  Table,
  Row,
  Col,
  Typography,
  Space,
  Button,
  Input,
  TreeSelect,
  Form,
  Modal,
  Spin,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import IconFont from "../../../../../../assets/ICON";
import { AjaxData } from "../../../../../../data/interface/publicInterface";
import {
  listToAntdTableTreeData,
  listToAntdTreeSelectTreeData,
} from "../../../../../../utils/common";
import {
  getfindAllDepartment,
  onDelete,
  AddDepartment,
  EditDepartment,
} from "../../../ServeApi";
import "./index.less";

const { Text } = Typography;

export interface DepartmentTreeTableProps {}

export interface DepartmentTreeTableState {}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};

@observer
class DepartmentTreeTable extends React.Component<
  DepartmentTreeTableProps,
  DepartmentTreeTableState
> {
  @observable private columns = [
    {
      title: "序号",
      dataIndex: "rank",
      key: "rank",
    },
    {
      title: "部门名称",
      dataIndex: "orgName",
      key: "orgName",
    },
    {
      title: "部门简称",
      dataIndex: "abbreviation",
      key: "abbreviation",
    },
    {
      title: "父级编号",
      dataIndex: "parentId",
      key: "parentId",
    },
    {
      title: "层级",
      dataIndex: "lev",
      key: "lev",
    },
    {
      title: "操作",
      dataIndex: "ii",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.onEdit(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.addDepartmentModal(record);
                }}
              >
                <IconFont type="icon_form_add" style={{ color: "#7B9AFC" }} />
                <Text>新增</Text>
              </span>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.onDelete(record);
                }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
                <Text>删除</Text>
              </span>
            </Space>
          </>
        );
      },
    },
  ];
  @observable private dataSouce: any = [];
  //add:新增，update:修改
  @observable protected Mod = "add";
  @observable private isModalVisible: boolean = false;
  @observable private prentNod: any = null; //新增或编辑信息参照本
  @observable private initValue: any = null; //编辑信息副本
  private TreeSelectTreeData: any = null; //父级数据tree
  @observable private listData: any = []; //请求接口来的原始数据
  private instance: any = null;
  state = { loading: false };
  render() {
    return (
      <>
        <div className="rowcon_body">
          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                this.addDepartmentModal();
              }}
            >
              新增
            </Button>
          </div>
          <div className="rowcon_bottom"></div>
          <Spin spinning={this.state.loading}>
            <Table
              columns={this.columns}
              dataSource={this.dataSouce}
              pagination={false}
            />
          </Spin>
          <Modal
            title={this.Mod === "add" ? "新增部门" : "编辑部门"}
            visible={this.isModalVisible}
            onOk={() => {
              this.handleOk();
            }}
            onCancel={() => {
              this.handleCancel();
            }}
          >
            <Form {...formItemLayout} ref={(el) => (this.instance = el)}>
              <Row>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="部门序号："
                    name="rank"
                    rules={[
                      {
                        required: true,
                        message: "请填写部门序号",
                      },
                      {
                        message: "部门序号应为数字",
                        pattern: new RegExp(/^[0-9]\d*$/, "g"),
                      },
                    ]}
                  >
                    <Input placeholder="部门序号" />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="部门名称："
                    name="orgName"
                    rules={[
                      {
                        required: true,
                        message: "请填写部门名称",
                      },
                    ]}
                  >
                    <Input placeholder="部门名称" />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="部门简称："
                    name="abbreviation"
                    rules={[
                      {
                        required: true,
                        message: "请填写部门简称",
                      },
                    ]}
                  >
                    <Input placeholder="部门简称" />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item label="父级部门：" name="parentId">
                    {/* <Input placeholder="父级部门" /> */}
                    <TreeSelect
                      treeData={this.TreeSelectTreeData}
                      onChange={(value: any) => {
                        this.onChange(value);
                      }}
                    ></TreeSelect>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
        </div>
      </>
    );
  }
  componentWillMount() {
    this.init();
  }
  init() {
    this.getData();
  }
  /**请求部分 */
  //请求数据
  async getData() {
    let _this = this;
    _this.setState({ loading: true });
    let prom: any = await getfindAllDepartment().catch((err) => {
      if (err) {
        console.log(err);
      }
    });
    if (prom) {
      let res: AjaxData = prom;
      if (res.success) {
        this.listData = res.data;
        this.TreeSelectTreeData = listToAntdTreeSelectTreeData(res.data);
        this.TreeSelectTreeData.push({ title: "根节点", value: null }); //添加无父节点的清空

        let souce = listToAntdTableTreeData(res.data);
        this.dataSouce = souce;
        _this.setState({ loading: false });
        this.forceUpdate();
      } else {
        Modal.warning({
          title: res.message,
          onOk() {
            _this.setState({ loading: false });
          },
        });
      }
    }
  }
  async DeleteDepartItem(pream) {
    let _this = this;
    _this.setState({ loading: true });
    let rtn: any = await onDelete(JSON.stringify(pream)).catch((err) => {});
    if (rtn) {
      let res: AjaxData = rtn;
      if (res.success) {
        _this.setState({ loading: false });
        this.init(); //初始化数据
      } else {
        Modal.error({
          title: res.message,
          onOk() {
            _this.setState({ loading: false });
          },
        });
      }
    }
  }
  async onDelete(item: DataItem) {
    let pream = { orgId: item.id };
    let _this = this;

    Modal.confirm({
      title: "是否确认删除部门",
      onOk: () => {
        _this.DeleteDepartItem(pream);
      },
    });
  }

  /**操作 */
  //表外新增
  addDepartmentModal(item?: DataItem) {
    this.Mod = "add";
    this.ChangeModalVisible();
    if (item) {
      setTimeout(() => {
        if (this.instance) {
          const container: any = (this.instance as any) as HTMLDivElement;
          container.setFieldsValue({ parentId: item.treeId });
        }
      });
    }
  }
  onEdit(item: DataItem) {
    this.Mod = "update";
    this.ChangeModalVisible();
    this.initValue = item;
    if (item) {
      setTimeout(() => {
        if (this.instance) {
          const container: any = (this.instance as any) as HTMLDivElement;
          container.setFieldsValue(item);
        }
      });
    }
  }
  //清空表单
  clearFromData() {
    if (this.instance) {
      const container: any = (this.instance as any) as HTMLDivElement;
      container.setFieldsValue({
        rank: undefined,
        orgName: undefined,
        abbreviation: undefined,
        parentId: undefined,
      });
    }
    this.prentNod = null;
  }
  //弹窗显示隐藏方法
  ChangeModalVisible() {
    this.prentNod = null; //清空新增编辑内容副本
    this.isModalVisible = !this.isModalVisible;
    this.setState({ loading: false });
    this.forceUpdate();
  }
  onChange(value: number | null) {
    if (value) {
      this.listData.map((item) => {
        if (item.treeId === value) {
          this.prentNod = item;
        }
        return item;
      });
      this.forceUpdate();
    }
  }
  //修改或者新增
  async setData(item: FromData) {
    let _this = this;
    for (let key in item) {
      item[key] = item[key] ? item[key] : null;
    }
    switch (this.Mod) {
      case "add":
        if (item.parentId) {
          let obj: DataItem = this.getParentItem(item.parentId);
          item["lev"] = obj.lev;
          item["levelIndex"] = obj.levelIndex;
        }

        try {
          _this.setState({ loading: true });
          let res: any = await AddDepartment(JSON.stringify(item)).catch(
            (err) => {
              console.log(err);
              _this.setState({ loading: false });
            }
          );
          let json: AjaxData = res;
          if (json.success) {
            _this.init(); //初始化数据
            _this.setState({ loading: false });
          } else {
            Modal.error({
              title: json.message,
              onOk: () => {
                _this.setState({ loading: false });
              },
            });
          }
        } catch (error) {
          Modal.error({
            title: "初始化程序失败，无法读取数据，请刷新页面。",
            onOk: () => {
              _this.setState({ loading: false });
            },
          });
          console.error(error);
        }
        break;
      case "update":
        item["id"] = this.initValue["id"];
        item["treeId"] = this.initValue["treeId"];

        try {
          _this.setState({ loading: true });
          let res: any = await EditDepartment(JSON.stringify(item)).catch(
            (err) => {
              console.log(err);
              _this.setState({ loading: false });
            }
          );
          let json: AjaxData = res;
          if (json.success) {
            _this.init(); //初始化数据
            _this.setState({ loading: false });
          } else {
            Modal.error({
              title: json.message,
              onOk: () => {
                _this.setState({ loading: false });
              },
            });
          }
        } catch (error) {
          Modal.error({
            title: "初始化程序失败，无法读取数据，请刷新页面。",
            onOk: () => {
              _this.setState({ loading: false });
            },
          });
          console.error(error);
        }
        break;
      default:
        break;
    }
  }
  getParentItem(parentId) {
    let oI: any = {};
    this.listData.map((item) => {
      if (item.treeId === parentId) {
        oI = item;
      }
      return item;
    });
    return oI;
  }
  //弹窗确定
  handleOk() {
    let _this = this;
    const container: any = (this.instance as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        _this.ChangeModalVisible();
        _this.setData(res);
        //清空表单
        _this.clearFromData();
        _this.prentNod = null;
      })
      .catch((err) => {
        console.log(err);
      });
  }
  //弹窗取消
  handleCancel() {
    this.ChangeModalVisible();
    this.clearFromData();
  }
}
interface FromData {
  abbreviation: string;
  orgName: string;
  parentId: number | null;
  rank: string;
}
interface DataItem {
  abbreviation: string | null;
  id: number;
  lev: number;
  levelIndex: string;
  orgName: string;
  parentId: number | null;
  rank: number;
  treeId: number;
}
export default DepartmentTreeTable;
